import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/home/authorize_bean.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/manage/adjust/adjustmodel.dart';
import 'package:opene/ui/manage/adjust/retallysubmitscreen.dart';
import 'package:toast/toast.dart';

class ReTallySkuScreen extends StatelessWidget {
  ReTally reTally;

  ReTallySkuScreen({this.reTally});

  @override
  Widget build(BuildContext context) {
    return ReTallySkuScreenPage(reTally: reTally);
  }
}

class ReTallySkuScreenPage extends StatefulWidget {
  ReTally reTally;

  ReTallySkuScreenPage({this.reTally});

  @override
  _ReTallySkuPageState createState() => _ReTallySkuPageState(reTally: reTally);
}

class _ReTallySkuPageState extends BaseState<ReTallySkuScreen> {
  ReTally reTally;
  List<InventoryListDTO> data = new List();

  _ReTallySkuPageState({this.reTally});

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Adjust Re-Tally: SKU";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    data = reTally.vos;
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                "IBLPN: ",
                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
              ),
              Expanded(
                child: Text(
                  Utils.getStringisEmpty(reTally.lpn),
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                ),
              ),
            ],
          ),
          Row(
            children: [
              Text(
                "Container: ",
                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
              ),
              Expanded(
                child: Text(
                  Utils.getStringisEmpty(reTally.containerNo),
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 5,
          ),
          ConstrainedBox(
            constraints: BoxConstraints(maxHeight: 35),
            child: TextField(
              controller: textEditingController,
              textInputAction: TextInputAction.search,
              onSubmitted: (String text) {
                print('Searching for $text');
                if (Utils.isEmpty(text)) {
                  return;
                }
                getReTallyScanSku(false,text);
              },
              // autofocus: true,
              decoration: InputDecoration(
                suffixIcon: IconButton(
                  padding: EdgeInsets.all(2.0),
                  icon: Icon(
                    Icons.qr_code_scanner,
                    size: 28,
                    color: MyAppTheme.nearlyBlue,
                  ),
                  onPressed: () {
                    // requestPermissions();
                    // Utils.scanBarcode(context);
                    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                      return ScanCode();
                    })).then((text) {
                      if (text == null) {
                        return;
                      }
                      setState(() {
                        textEditingController.text = text;
                      });
                      print(text); //拿到扫描结果
                      getReTallyScanSku(false,text);
                    });
                  },
                ),
                border: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: MyAppTheme.nearlyBlue,
                  ),
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                  // 设置焦点之外的边框颜色
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                  // 设置焦点时的边框颜色
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                hintText: "scan product sku barcode",
                filled: true,
                fillColor: MyAppTheme.white,
                //隐藏下划线
                //border: InputBorder.none,
                hintStyle: TextStyle(color: Colors.grey),
                contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
              ),
              onChanged: (text) {
                code = text;
              },
            ),
          ),
          SizedBox(
            height: 5,
          ),
          Row(
            children: [
              Text(
                "SKU: ",
                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
              ),
              Expanded(
                child: Text(
                  Utils.getStringisEmpty(reTally.sku),
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                ),
              ),
            ],
          ),
          Text(
            "Tally Detail Recently:",
            style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
          ),
          SizedBox(
            height: 5,
          ),
          Expanded(child: setListView())
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      shrinkWrap: true,
      // physics: NeverScrollableScrollPhysics(),
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        InventoryListDTO trk = data[index];
        return Column(
          children: [
            Row(
              children: [
                Expanded(
                    flex: 1,
                    child: GestureDetector(
                      onTap: () {
                        setState(() {
                        });
                      },
                      child: Text(
                        Utils.getStringisEmpty(trk.sku),
                        style: MyAppTheme.test12,
                      ),
                    ),),
              ],
            ),
            Divider(),
          ],
        );
      },
    );
  }

  void getReTallyScanSku(bool isNext,String trackingCode) async {
    updateHint('');
    Map<String, dynamic> map = new HashMap();
    if (reTally.tallyTaskId != null) {
      map["tallyTaskId"]= reTally.tallyTaskId;
    }
    map["notifyId"] = reTally.notifyId;
    map["lpn"] = reTally.lpn;
    map["sku"] = trackingCode;

    String url = Constants.reTallyScanSku;
    int version = 0;
    try {
      if (Constants.jumpMapBean != null) {
        List<JumpBean> data = Constants.jumpMapBean.MANAGE_Adjustment.data;
        for (JumpBean jumpBean in data) {
          if (jumpBean.name =="ReTally") {
            version = jumpBean.version;
          }
        }
      }
    } catch (e) {
      e.printStackTrace();
    }
    if (version == 2) {
      url = Constants.reTally_v2_scanSku;
    }

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, url, params: map);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      ReTally reTallyTemp = ReTally.fromJson(baseResponse.data);
      // if(isNext){
        reTally.barcode=trackingCode;
        reTally.sku=reTallyTemp.sku;
        reTally.upType=reTallyTemp.upType;
        reTally.ctnQty=reTallyTemp.ctnQty;
        reTally.pcsQty=reTallyTemp.pcsQty;
        reTally.quantity=reTallyTemp.quantity;

        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => ReTallySubmitScreen(reTally:reTally)),
        );
      // }else{
      //   setState(() {
      //     reTally =reTallyTemp;
      //     if(reTally.vos!=null){
      //       data = reTally.vos;
      //     }
      //   });
      //
      // }
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void reTallyScanLpn(String lpn) async {
    updateHint('');
    Map<String, dynamic> map = new HashMap();
    map["lpn"] = lpn;

    String url = Constants.reTallyScanLpn;

    int version = 0;
    try {
      if (Constants.jumpMapBean != null) {
        List<JumpBean> data = Constants.jumpMapBean.MANAGE_Adjustment.data;
        for (JumpBean jumpBean in data) {
          if (jumpBean.name =="ReTally") {
            version = jumpBean.version;
          }
        }
      }
    } catch (e) {
      e.printStackTrace();
    }
    if (version == 2) {
      url = Constants.reTally_v2_scanLpn;
    }
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, url, params: map);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      setState(() {
        reTally = ReTally.fromJson(baseResponse.data);
        reTally.lpn = lpn;
        data = reTally.vos;
      });

    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  @override
  void setNext() {
    if (Utils.isEmpty(textEditingController.text)) {
      ToastContext().init(context);
      Toast.show("scan product sku barcode", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    getReTallyScanSku(true,textEditingController.text);
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
    });
  }
}
